package com.cc.demo.service;

import com.cc.demo.entity.Message;
import com.cc.demo.mapper.MessageMapper;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import static com.cc.demo.entity.table.MessageTableDef.MESSAGE;


@Service
public class MessageService {

    @Autowired
    private MessageMapper messageMapper;

    //分页查询，得先创建QueryWrapper排序，再查询
    public Page<Message> list(int currentPage, int pageSize) {
        QueryWrapper queryWrapper = QueryWrapper.create()
                .orderBy(MESSAGE.CREATE_TIME.desc())
                .orderBy(MESSAGE.ID.desc());


        Page<Message> page = new Page<>(currentPage, pageSize);
        return messageMapper.paginate(page, queryWrapper);
    }

    //根据ID查询留言
    public Message getById(Long id){
        QueryWrapper queryWrapper = QueryWrapper.create()
                .where(MESSAGE.ID.eq(id))
                .and(MESSAGE.DELETE.eq(false));
        return messageMapper.selectOneByQuery(queryWrapper);
    }

    //保留留言
    public boolean save(Message message){
        //设置留言更新时间
//        message.setCreateTime(java.time.LocalDateTime.now());
//        message.setUpdateTime(java.time.LocalDateTime.now());

        //默认状态为true，未删除
        if (message.getStatus() == null){
            message.setStatus(true);
        }
        if (message.getDelete() == null){
            message.setDelete(false);
        }

        return messageMapper.insert(message) > 0;
    }

    //更新留言
    public boolean update(Message message){
        //设置更新时间
        message.setUpdateTime(java.time.LocalDateTime.now());
        return messageMapper.update(message) > 0;
    }

    //根据ID删除留言(逻辑删除)
    public boolean deleteById(Long id){
        Message message = new Message();
        message.setId(id);
        message.setDelete(true);
        message.setUpdateTime(java.time.LocalDateTime.now());
        return messageMapper.update(message) > 0;
    }


    //根据条件查询留言
    public Page<Message> searchByCondition(String keyword, int currentPage, int pageSize){
        QueryWrapper queryWrapper = QueryWrapper.create()
                .where(MESSAGE.DELETE.eq( false))
                .and(MESSAGE.CONTENT.like(keyword))
                    .or(MESSAGE.NICKNAME.like(keyword))

                .orderBy(MESSAGE.CREATE_TIME.desc())
                .orderBy(MESSAGE.ID.desc());

        Page<Message> page = new Page<>(currentPage, pageSize);
        return messageMapper.paginate(page, queryWrapper);
    }
}
